package ormap.skywalker.callhelper;

import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import db.skywalker.callhelper.DB;
import entity.skywalker.callhelper.UserDataReportEntity;

@TargetApi(16)
public class UserDataReportOR
{
	private final String STR_TABLE_NAME = "user_data_report";
	private final String STR_COLUMNS_REPORT_ID = "report_id";
	private final String STR_COLUMNS_DEVICE_ID = "device_id";
	private final String STR_COLUMNS_COUNT = "count";
	private final String STR_COLUMNS_REPORT_TIME = "report_time";
	private final String STR_COLUMNS_IS_REPORT = "is_report";
	
	private SQLiteDatabase db;
	private DB database;
	
	public UserDataReportOR(Context context)
	{
		database = new DB(context);
	}
	
	public void open()
	{
		db = database.open();
	}
	
	public void close()
	{
		if (null != database)
		{
			database.close();
		}
	}
	
	public long insert(UserDataReportEntity userDataReportEntity)
	{
		ContentValues cv = new ContentValues();
		cv.put(STR_COLUMNS_DEVICE_ID, userDataReportEntity.getDeviceId());
		cv.put(STR_COLUMNS_REPORT_ID, String.valueOf(userDataReportEntity.getReportId()));
		cv.put(STR_COLUMNS_COUNT, String.valueOf(userDataReportEntity.getCount()));
		cv.put(STR_COLUMNS_REPORT_TIME, userDataReportEntity.getReportTime());
		cv.put(STR_COLUMNS_IS_REPORT, userDataReportEntity.getIsReport());
		return db.insert(STR_TABLE_NAME, null, cv);
	}
	
	public int delete(UserDataReportEntity userDataReportEntity)
	{
		return db.delete(STR_TABLE_NAME, 
				    "_id = " + String.valueOf(userDataReportEntity.getId()), 
				    null);
	}
	
	public Cursor query(long id)
	{
		return db.query(true, STR_TABLE_NAME, null, 
				"_id = " + String.valueOf(id), null, 
				null, null, null, null, null);
	}
	
	public Cursor query(int reportId, String reportTime)
	{
		String[] str = {String.valueOf(reportId), reportTime};
		Log.d("UserDataReportOR-query", reportTime);
		return db.rawQuery("select * from " + STR_TABLE_NAME
				+ " where report_id = ? and report_time = ? ",
				str);
	}
	
	public boolean IsReportToday(UserDataReportEntity udrEntity)
	{
		Cursor cursor = query(udrEntity.getReportId(), udrEntity.getReportTime());
		cursor.moveToFirst();
		
		if (cursor.getCount() > 0)
		{
			cursor.close();
			return true;
		}
		else
		{
			cursor.close();
			return false;
		}
	}
}